package clientsController;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;

public class ClientThread extends Thread {
	
	private String identifier;
	private ObjectOutputStream bufferOut;
	private ObjectInputStream bufferIn;
	private HashMap<Integer, Task> tasks;
	
	public ClientThread(String sensorCode, ObjectOutputStream bufferOut, ObjectInputStream bufferIn) throws IOException {
		this.identifier = sensorCode;
		this.bufferOut = bufferOut;
		this.bufferIn = bufferIn;
		
		this.tasks = new HashMap<Integer, Task>();
		this.finishHandshake();
	}
	
	private void finishHandshake() {
		try {
			this.bufferOut.writeObject("ok");
		}
		catch (IOException e) {
			System.out.println("ClientThread:: " + e);
		}
	}
	
	private void createTask(String message) {
		Task task = new Task(this.identifier, this.getBufferOut(), message);
		this.tasks.put(task.getIdentifier(), task);
		task.start();
	}
	
	@Override
	public void run() {
		while (true) {
			String message = null;
			try {
				message = (String) this.getBufferIn().readObject();
				if (message == null) {
					continue;
				}
			}
			catch (IOException e) {
				System.err.println("ClientThread:: " + e);
				return;
			}
			catch (ClassNotFoundException e) {
				System.err.println("ClientThread:: " + e);
				System.exit(1);
			}
			
			this.createTask(message);
		}
	}	
	
	@Override
	public String toString() {
		return "Client id: " + this.identifier;
	}

	public String getIdentifier() {
		return this.identifier;
	}

	public ObjectOutputStream getBufferOut() {
		return this.bufferOut;
	}

	public ObjectInputStream getBufferIn() {
		return this.bufferIn;
	}
	
	public HashMap<Integer, Task> getTasks() {
		return tasks;
	}
}
